package com.szqhyxj.youxiangju.biz.web;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.szqhyxj.youxiangju.BaseActivity;
import com.szqhyxj.youxiangju.BuildConfig;
import com.szqhyxj.youxiangju.R;
import com.szqhyxj.youxiangju.biz.core.TokenManager;
import com.szqhyxj.youxiangju.biz.login.LoginActivity;
import com.szqhyxj.youxiangju.biz.merchantHome.MerchantContainerActivity;
import com.szqhyxj.youxiangju.biz.merchantHome.MerchantType;
import com.szqhyxj.youxiangju.sys.components.NavigationBar;

import butterknife.BindView;
import butterknife.ButterKnife;


public class ApplyCardMyWebActivity extends BaseActivity implements NavigationBar.NavigationBarListener {

    @BindView(R.id.navigationBar)
    NavigationBar navigationBar;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.web)
    MyWebView web;
    private static final String EXIT = "exit";

    private int exit = WebExit.FINISH.getCode();


    public static void start(Activity activity, String title, String url) {
        Intent intent = new Intent();
        intent.setClass(activity, ApplyCardMyWebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        activity.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        ButterKnife.bind(this);

        initViews();
        initDatas();
        initEvent();
        exit = getIntent().getIntExtra(EXIT, WebExit.FINISH.getCode());

    }

    private void initViews() {
        this.web.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                sslErrorHandler.proceed();//接受信任所有网站的证书
            }

            //拦截HTML页面中的点击事件
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                web.loadUrl(url);
                return false;

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                super.onPageStarted(view, url, favicon);
            }
        });
        //加载页面进度条
        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                if (newProgress == 100 && progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
            }
        });
    }


    @SuppressLint("NewApi")
    private void initDatas() {
        String url = getIntent().getStringExtra("url");
        String title = getIntent().getStringExtra("title");

        if (title == null) {
            navigationBar.setVisibility(View.GONE);
        } else {
            navigationBar.setNaviTitle(title);
        }

        web.loadUrl(url);
        WebSettings webSettings = this.web.getSettings();

        // 修改ua使得web端正确判断
        web.getSettings().setUserAgentString("youxiangju");

        //设置为可调用js方法
        webSettings.setJavaScriptEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

        web.evaluateJavascript("sum(1,2)", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                Log.e("dgj", "onReceiveValue value=" + value);
            }
        });
        web.addJavascriptInterface(this, "getLoadData");
    }

    private void initEvent() {
        navigationBar.setNavigationBarListener(this);
    }

    @Override
    public void navigationLeft() {
        if (web.getUrl().equals("https://wm.cib.com.cn/html/webapp/fast-issue/parnter.html?id=65b1f3b5eba146789832f50b257d8d1d") || web.getUrl().equals("https://xyk.cebbank.com/cebmms/apply/ps/card-list.htm?pro_code=FHTG067632SA0188CYJR")) {
            finish();
        } else {
            web.goBack();
        }
    }

    @Override
    public void navigationRight() {
    }

    //设置返回键动作（防止按返回键直接退出程序)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (web.getUrl().equals("https://wm.cib.com.cn/html/webapp/fast-issue/parnter.html?id=65b1f3b5eba146789832f50b257d8d1d") || web.getUrl().equals("https://xyk.cebbank.com/cebmms/apply/ps/card-list.htm?pro_code=FHTG067632SA0188CYJR")) {
                finish();
            } else {
                web.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @JavascriptInterface
    public String getToken() {
        Log.w("tag", "token:" + TokenManager.INSTANCE.getMToken());
        return TokenManager.INSTANCE.getMToken();
    }

    @JavascriptInterface
    public void finishTist() {
        finish();
    }

    @Override
    public void finish() {
        if (exit == WebExit.FINISH.getCode()) {
            super.finish();
            return;
        }
        if (exit == WebExit.PLAN_LIST.getCode()) {
            MerchantContainerActivity.start(this, false, MerchantType.PLAN.getCode());
            super.finish();
        }
    }

    @JavascriptInterface
    public void jump() {

    }

    @JavascriptInterface
    public void outLogin() {
        TokenManager.INSTANCE.clear();
        LoginActivity.start(this);
    }

    @JavascriptInterface
    public void gobackToMyRootView() {
        finish();
    }
}
